var mysqlUtil = require('./mysqlUtil');
var EventProxy = require('eventproxy');
var sqlParamPrefix = '->';

/**
 * 分页查询
 * 
 * @param  {[type]} sql [description]
 * @param  {[type]} req [description]
 * @param  {[type]} res [description]
 * @return {[type]}     [description]
 */
var partitionQuery = function(sql, req, res) {
    sql = sql.replace(/  */g, " ");
    var pageIndex = req.body.pageIndex || 1;
    var pageSize = req.body.pageSize || 20;
    var sortField = req.body.sortField || '';
    var sortOrder = req.body.sortOrder || 'asc';

    var proxy = new EventProxy();
    proxy.all('total', 'datas', function(data1, data2) {
        var obj = {
            datas: data2,
            pageIndex: pageIndex,
            pageSize: pageSize,
            sortField: sortField,
            sortOrder: sortOrder,
            total: data1[0].total
        };
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(obj));
    });

    mysqlUtil.exec('select count(*) as total from (' + sql + ') as t', [], function(err, result) {
        proxy.emit('total', result);
    });

    if (sortField !== '') {
        sql = sql.substring(0, sql.indexOf('order by'));
        sql += 'order by ' + sortField + ' ' + sortOrder;
    }
    sql += ' limit ' + (pageIndex - 1) * pageSize + ',' + pageSize;
    mysqlUtil.exec(sql, [], function(err, result) {
        proxy.emit('datas', result);
    });
};

/**
 * 保存
 * 
 * @param  {[type]} tableName [表名]
 * @param  {[type]} aliesName [别名]
 * @param  {[type]} req       [request]
 * @param  {[type]} afterFunc       [完成后执行的事件]
 * @return {[type]}           [description]
 */
var save = function(tableName, aliesName, req, afterFunc) {
    var data = req.body;

    //检查新增还是修改
    var id = (aliesName != null) ? req.body[aliesName + '.id'] : req.body['id'];
    if (id == null || id == '') {
        insert(tableName, aliesName, req, afterFunc);
    } else {
        update(tableName, aliesName, req, afterFunc);
    }
};

var insert = function(tableName, aliesName, req, afterFunc) {
    var data = paramsFilter(req.body, aliesName);
    if (data.id == null || data.id == '') {
        data.id = getUuid();
    }

    var params = [];
    var sql = "insert into " + tableName + " (";
    for (var d in data) {
        sql += d + ",";
    }
    sql = sql.substring(0, sql.length - 1);
    sql += ") values (";
    for (var d in data) {
        if (typeof data[d] === "string" && data[d].indexOf(sqlParamPrefix) != -1) {
            sql += data[d].replace(sqlParamPrefix, '') + ",";
        } else {
            sql += "?,"
            params.push(data[d]);
        }
    }
    sql = sql.substring(0, sql.length - 1);
    sql += ")";

    mysqlUtil.exec(sql, params, function(err, result) {
        if (afterFunc != null) {
            afterFunc(err, result);
        }
    });
};

var update = function(tableName, aliesName, req, afterFunc) {
    var data = paramsFilter(req.body, aliesName, aliesName + '.id');
    var id = req.body[aliesName + '.id'] || '';
    var params = [];
    var sql = "update " + tableName + " set ";

    for (var d in data) {
        if (typeof data[d] === "string" && data[d].indexOf(sqlParamPrefix) != -1) {
            sql += d + "=" + data[d].replace(sqlParamPrefix, '') + ",";
        } else {
            sql += d + "=?,";
            params.push(data[d]);
        }
    }
    sql = sql.substring(0, sql.length - 1);
    sql += " where id=?";
    params.push(id);

    mysqlUtil.exec(sql, params, function(err, result) {
        if (afterFunc != null) {
            afterFunc(err, result);
        }
    });
};

/**
 * 参数过滤
 * @param  {[type]} params    [参数]
 * @param  {[type]} aliesName [别名]
 * @param  {[type]} ignores   [忽略的参数名]
 * @return {[type]}           [description]
 */
var paramsFilter = function(params, aliesName, ignores) {
    var result = {};
    var ignores_arr = ignores != null ? ignores.split(',') : [];
    for (var p in params) {
        var is_ignore = false;
        for (var i = 0; i < ignores_arr.length; i++) {
            if (ignores_arr[i] === p) {
                is_ignore = true;
                break;
            }
        }
        if (!is_ignore && p.indexOf(aliesName + '.') != -1) {
            result[p.substring(p.indexOf(aliesName + '.') + aliesName.length + 1, p.length)] = params[p];
        }
    }
    return result;
};

/**
 * 获取uuid
 * @returns {string}
 */
var getUuid = function() {
    var s = [];
    var hexDigits = "0123456789abcdef";
    for (var i = 0; i < 36; i++) {
        s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
    }
    s[14] = "4";
    s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1);
    //s[8] = s[13] = s[18] = s[23] = "-";
    s[8] = s[13] = s[18] = s[23] = "";

    var uuid = s.join("");
    return uuid;
};

exports.partitionQuery = partitionQuery;
exports.save = save;
exports.insert = insert;
exports.update = update;
exports.getUuid = getUuid;
